# 导入所需的库
from tensorflow.examples.tutorials.mnist import input_data  # 导入MNIST数据集
import numpy as np  # 导入numpy库
import tensorflow.compat.v1 as tf  # 导入TensorFlow 1.x版本，禁用2.x版本特性
from tqdm import tqdm  # 导入进度条库
import matplotlib.pyplot as plt  # 导入绘图库
import time  # 导入时间库

# 设置matplotlib中文显示
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

tf.disable_v2_behavior()# 禁用TensorFlow 2.x的默认行为，使用1.x的API

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)# 读取MNIST数据集

# 设置超参数
learning_rate = 1e-4  # 学习率
keep_prob_rate = 0.7  # Dropout比例
max_epoch = 1000  # 最大训练周期数
P = 100  # 每P个batch记录一次训练和测试准确率

def weight_variable(shape):# 定义权重变量初始化函数
    initial = tf.truncated_normal(shape, stddev=0.1)  # 截断正态分布初始化
    return tf.Variable(initial)

def bias_variable(shape):# 定义偏置变量初始化函数
    initial = tf.constant(0.1, shape=shape)  # 常数初始化
    return tf.Variable(initial)

def conv2d(x, W):# 定义2D卷积函数
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):# 定义2x2最大池化函数
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def compute_accuracy(v_xs, v_ys):# 定义计算准确率的函数
    y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})    # 使用全局变量prediction进行预测

    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))    # 计算预测正确的标签数

    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))    # 计算准确率

    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})    # 运行准确率计算图，并返回结果
    return result

# 定义输入占位符
xs = tf.placeholder(tf.float32, [None, 784], name='x_input')
ys = tf.placeholder(tf.float32, [None, 10], name='y_input')
keep_prob = tf.placeholder(tf.float32)

x_image = tf.reshape(xs, [-1, 28, 28, 1])# 将输入数据重塑为28x28的图像
W_conv1 = weight_variable([5, 5, 1, 32])# 定义第一层卷积层的权重和偏置
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)# 应用第一层卷积和ReLU激活函数
h_pool1 = max_pool_2x2(h_conv1)# 应用第一层池化
W_conv2 = weight_variable([5, 5, 32, 64])# 定义第二层卷积层的权重和偏置
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)# 应用第二层卷积和ReLU激活函数
h_pool2 = max_pool_2x2(h_conv2)# 应用第二层池化

# 定义全连接层的权重和偏置
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])# 将池化层的输出扁平化为全连接层的输入
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)# 应用全连接层和ReLU激活函数
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)# 应用Dropout

# 定义输出层的权重和偏置
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)# 应用全连接层和softmax激活函数得到预测结果

cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))# 定义交叉熵损失函数
train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)# 定义优化器

accuracy_history = []# 初始化准确率历史记录列表

# 定义计算准确率的函数，用于训练和测试
def compute_accuracy(sess, xs, ys, keep_prob, prediction, test_images, test_labels):
    correct_predictions = tf.equal(tf.argmax(prediction, 1), tf.argmax(test_labels, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
    return sess.run(accuracy, feed_dict={xs: test_images, ys: test_labels, keep_prob: 1.0})


saver = tf.train.Saver()# 创建模型保存器

train_accuracy_history = []# 初始化训练准确率历史记录列表
test_accuracy_history = []# 初始化测试准确率历史记录列表

# 启动TensorFlow会话
with tf.Session() as sess:
    init = tf.global_variables_initializer()    # 初始化全局变量
    sess.run(init)

    start = time.time()    # 记录开始时间
    # 训练循环
    for i in tqdm(range(max_epoch), desc="训练进度"):
        batch_xs, batch_ys = mnist.train.next_batch(100)        # 获取一个批次的数据
        sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: keep_prob_rate})        # 执行训练步骤

        # 每P个batch记录一次训练和测试准确率
        if (i + 1) % P == 0:
            # 计算并记录训练准确率
            train_accuracy = compute_accuracy(sess, xs, ys, keep_prob, prediction, batch_xs, batch_ys)
            train_accuracy_history.append(train_accuracy)

            # 计算并记录测试准确率
            test_accuracy = compute_accuracy(sess, xs, ys, keep_prob, prediction, mnist.test.images, mnist.test.labels)
            test_accuracy_history.append(test_accuracy)

            print("训练次数: {}, 训练准确率: {:.2f}%, 测试准确率: {:.2f}%".format(i + 1, train_accuracy * 100, test_accuracy * 100))            # 打印当前训练次数、训练准确率和测试准确率


    end = time.time()    # 记录结束时间
    print("\n最终训练准确率: {:.2f}%".format(train_accuracy * 100))#打印最终训练准确率
    print("训练用时: {:.2f} seconds".format(end - start))#打印训练用时
    print("\n最终测试准确率: {:.2f}%".format(test_accuracy * 100))    # 打印最终测试准确率

    save_path = saver.save(sess, "./mnist_model.ckpt")    # 保存模型

    # 绘制训练准确率变化曲线
    plt.figure(figsize=(6, 4))
    plt.plot(range(P, max_epoch + 1, P), train_accuracy_history, marker='o', color='#004098', linestyle='-')
    plt.xlabel('训练次数', fontsize=14)
    plt.ylabel('训练准确率', fontsize=14)
    plt.title('训练准确率变化曲线', fontsize=16)
    plt.grid(True)
    plt.show()

    # 绘制测试准确率变化曲线
    plt.figure(figsize=(6, 4))
    plt.plot(range(P, max_epoch + 1, P), test_accuracy_history, marker='o', color='#ba2a17', linestyle='-')
    plt.xlabel('测试次数', fontsize=14)
    plt.ylabel('测试准确率', fontsize=14)
    plt.title('测试准确率变化曲线', fontsize=16)
    plt.grid(True)
    plt.show()

    saver.restore(sess, save_path)    # 加载保存的模型

    # 随机选择5张测试图片进行预测
    num_predictions = 5
    selected_indices = np.random.choice(mnist.test.images.shape[0], num_predictions, replace=False)
    selected_images = mnist.test.images[selected_indices]
    selected_images_reshaped = selected_images.reshape(num_predictions, 784)


    prediction_results = sess.run(prediction, feed_dict={xs: selected_images_reshaped, keep_prob: 1.0})# 执行预测
    predicted_labels = np.argmax(prediction_results, axis=1)# 获取预测的最大值索引作为预测标签

    # 显示预测的图片和结果
    for i, idx in enumerate(selected_indices):
        plt.subplot(1, num_predictions, i + 1)
        plt.imshow(selected_images[i].reshape(28, 28), cmap='gray')
        plt.title("实值标签: %d\n预测值: %d" % (np.argmax(mnist.test.labels[idx]), predicted_labels[i]))
        plt.axis('off')
    plt.show()